package testJdk.loops.iterator;

import com.google.common.collect.Lists;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Iterator;

/**
 * @version 1.0.0
 * Created by cyd on 2022-06-20 11:38:23
 * @ClassName : learn_jdk.loops.iterator.TestIterator
 * @Description : 迭代器编译元素，并修改
 */
public class TestIterator {

    /**
     * 迭代器中删除元素，集合也会跟着删除
     */
    @Test
    public void test() {
        ArrayList<Integer> list = Lists.newArrayList(1, 2, 3, 4, 5);
        Iterator<Integer> iterator = list.iterator();
        while (iterator.hasNext()) {
            Integer num = iterator.next();
            System.out.println(num);
            if (num.equals(5)) {
                iterator.remove();
            }
        }
        System.out.println(list);
    }

    /**
     * 在迭代器中不能直接删除集合中的元素，会报非法修改异常
     */
    @Test
    public void test2() {
        ArrayList<Integer> list = Lists.newArrayList(1, 2, 3, 4, 5);
        Iterator<Integer> iterator = list.iterator();
        while (iterator.hasNext()) {
            Integer num = iterator.next();
            System.out.println(num);
            if (num.equals(5)) {
                list.remove(num);
            }
        }
        System.out.println(list);
    }
}
